package hang.xipujewelWeb.web.account;

import hang.xipujewelWeb.entity.account.User;
import hang.xipujewelWeb.entity.app.Ring;
import hang.xipujewelWeb.entity.app.RingType;
import hang.xipujewelWeb.entity.app.ShoppingCart;
import hang.xipujewelWeb.service.account.RingManager;
import hang.xipujewelWeb.service.account.RingTypeManager;
import hang.xipujewelWeb.service.account.ShoppingCartManager;
import hang.xipujewelWeb.service.account.UserManager;
import hang.xipujewelWeb.utils.FileUtil;
import hang.xipujewelWeb.utils.UserUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esoar.modules.web.BaseController;
import net.esoar.modules.web.pojo.JPage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("ring")
public class RingController extends BaseController<Ring> {

	@Autowired
	private RingManager ringManager;

	@Autowired
	private UserManager userManager;

	@Autowired
	private RingTypeManager ringTypeManager;

	@Autowired
	private ShoppingCartManager shoppingCartManager;

	private static final Integer pageSize = 16;

	@RequestMapping("")
	public String list(Model model, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		initOrder("id", JPage.ASC);
		User cUser = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		List<RingType> ringTypes = ringTypeManager.getAllOrderById();
		model.addAttribute("cUser", cUser);
		model.addAttribute("ringTypes", ringTypes);
		//		model.addAttribute("ringType", (String) searchParams.get("EQ_ringType.id"));
		model.addAttribute("ringBaseNumber", cUser.getPriceBaseNumber().getRingBaseNumber());
		jPage.setPageSize(pageSize);

		jPage = ringManager.search(searchParams, jPage);
		if (cUser.getType() == 2) {
			for (Ring ring : jPage.getResult()) {
				float secondPrice = ring.getPrice() * cUser.getParent().getPriceBaseNumber().getRingBaseNumber();
				ring.setSecondPrice(secondPrice);
			}
		}
		model.addAttribute("rings", jPage.getResult());

		return "ring/ring-list";
	}

	@RequestMapping(value = "search")
	public String search(Model model, @RequestParam("typeName") String typeName, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		if (!"显示全部".equals(typeName)) {
			searchParams.put("EQ_ringType.name", typeName);
		}
		User cUser = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		jPage.setPageSize(pageSize);
		List<Ring> rings = ringManager.search(searchParams, jPage).getResult();

		if (cUser.getType() == 2) {
			for (Ring ring : rings) {
				float secondPrice = ring.getPrice() * cUser.getParent().getPriceBaseNumber().getRingBaseNumber();
				ring.setSecondPrice(secondPrice);
			}
		}
		model.addAttribute("rings", rings);

		return "ring/ring-search-list";
	}

	@RequestMapping(value = "more")
	public String more(Model model, @RequestParam("typeName") String typeName, @RequestParam("page") String page,
			ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		int pageNum = Integer.parseInt(page);
		if (!"显示全部".equals(typeName)) {
			searchParams.put("EQ_ringType.name", typeName);
		}
		User cUser = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		jPage.setPageSize(pageSize);
		jPage.setPageNo(pageNum);
		List<Ring> rings = ringManager.search(searchParams, jPage).getResult();

		if (cUser.getType() == 2) {
			for (Ring ring : rings) {
				float secondPrice = ring.getPrice() * cUser.getParent().getPriceBaseNumber().getRingBaseNumber();
				ring.setSecondPrice(secondPrice);
			}
		}
		model.addAttribute("rings", rings);

		return "ring/ring-more-list";
	}

	@RequestMapping(value = "detail/{id}")
	public String input(@PathVariable(ID) Long id, Model model) {
		Ring ring = ringManager.get(id);
		User cUser = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		if (cUser.getType() == 2) {
			float secondPrice = ring.getPrice() * cUser.getParent().getPriceBaseNumber().getRingBaseNumber();
			ring.setSecondPrice(secondPrice);
		}
		model.addAttribute("ring", ring);
		model.addAttribute("cUser", cUser);
		return "ring/ring-detail";
	}

	@RequestMapping(value = "getImage", method = RequestMethod.GET)
	@ResponseBody
	public void getImage(@RequestParam("photo") String photo, HttpServletRequest httpRequest,
			HttpServletResponse response) throws IOException {
		//		HttpHeaders headers = new HttpHeaders();
		//		headers.setContentType(MediaType.IMAGE_JPEG);
		//		headers.setContentDispositionFormData("attachment", "ring.jpg");
		//		return new ResponseEntity<byte[]>(FileUtil.download(this.getServerPath(httpRequest), photo), headers,
		//				HttpStatus.OK);
		response.setContentType("image/*"); // 设置返回的文件类型
		response.setHeader("Content-disposition", "attachment; filename=" + photo);
		OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
		toClient.write(FileUtil.download(this.getServerPath(httpRequest), photo)); // 输出数据
		toClient.close();
	}

	@RequestMapping("addShopCar")
	@ResponseBody
	public String addShopCar(@RequestParam("id") long id) {
		Ring ring = ringManager.get(id);
		ShoppingCart shoppingCart = new ShoppingCart();
		User user = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		List<ShoppingCart> shoppingCart2 = shoppingCartManager.findByUesrAndRing(user.getId(), ring.getId());

		if (shoppingCart2 != null && shoppingCart2.size() > 0) {
			return "" + ring.getNo() + "已经在购物车中";
		} else {
			shoppingCart.setRing(ring);
			shoppingCart.setUesr(user);
			shoppingCart.setAddTime(new Date());
			shoppingCartManager.save(shoppingCart);
		}

		return "加入购物车成功";
	}

	@Override
	public String baseMapping() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getModelName() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getServerPath(HttpServletRequest httpRequest) {
		String path = httpRequest.getSession().getServletContext().getRealPath("/WEB-INF");
		path = path.replaceAll("xipujewelWeb", "xipujewel");
		//		path = path.replaceAll(":8089", ":8080");
		return path;
	}

}
